package GUI;

import Ctr.ProductCtr;
import Ctr.SalesOrderCtr;
import Model.Product;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;

public class ProductSearch extends JDialog {
    private JPanel contentPane;
    private JButton btnAddProduct;
    private JButton btnCancel;
    private JTextField txtFindProductByName;
    private JTable tblSearchResults;
    private JTextField txtProductAmount;
    private JLabel lblProductSearchAmount;
    private JButton btnFindProductByName;

    private ProductCtr productCtr;
    private SalesOrderCtr salesOrderCtr;

    public ProductSearch(SalesOrderCtr salesOrderCtr1) {

        productCtr = new ProductCtr();
        salesOrderCtr = salesOrderCtr1;

        setContentPane(contentPane);
        setModal(true);
        getRootPane().setDefaultButton(btnAddProduct);
        setSize(new Dimension(450,600));
        setResizable(false);
        setTitle("Product search");

        btnAddProduct.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                findProduct();
            }
        });

        btnCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });

        // call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    onCancel();
                }
        });

        txtFindProductByName.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                txtFindProductByName.setText("");
            }
        });

        txtFindProductByName.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                createSearchList();
                super.keyReleased(e);
            }
        });
    }

    private void createSearchList() {
        ArrayList<Product> products = productCtr.findProducts(txtFindProductByName.getText(), true);
        SearchResultsTableModel model = new SearchResultsTableModel();
        model.setData(products);
        tblSearchResults.setModel(model);
    }

    private void findProduct() {
        salesOrderCtr.addProductToSalesOrder(Integer.parseInt(tblSearchResults.getValueAt(tblSearchResults.getSelectedRow(), 0).toString()), Integer.parseInt(txtProductAmount.getText()));
    }



    private void onCancel() {
// add your code here if necessary
        dispose();
    }
}
